<template>
  <div class="parent-container">
    <div class="form-container">
      <h1 class="center-head">户口迁出办理</h1>

      <!-- 表单0,问题见621 -->
      <!-- label-width设置表单内标签的宽度 -->
      <el-form
        :model="formData"
        :rules="rulesFormData"
        ref="formRefData"
        label-width="140px"
        class="center-line"
      >
        <el-row>
          <el-col :span="10">
            <el-form-item label="输入居民身份证号" prop="idNumber">
              <el-input v-model="formData.idNumber"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-button type="primary" @click="handleSearch"
                >搜索</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <br /><br />

      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="80px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="身份证号" prop="idNumber">
              <el-input v-model="form.idNumber" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="派出所" prop="stationName">
              <el-input
                v-model="form.stationName"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所在户号" prop="householdNumber">
              <el-input
                v-model="form.householdNumber"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="gender">
              <el-input v-model="form.gender" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="民族" prop="ethnicity">
              <el-input v-model="form.ethnicity" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="变动日期" prop="changeDate">
              <el-date-picker
                v-model="form.changeDate"
                type="date"
                placeholder="选择日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="变动类别" prop="changeType">
              <el-input v-model="form.changeType" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="变动原因" prop="description">
              <el-input v-model="form.description"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button
            type="primary"
            @click="onSubmit"
            class="submit-button"
            >新建记录</el-button
          >
          <el-button type="primary" @click="reset" plain
            >重置信息</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { getPopulation } from "../../../api/epgms/population/get.js";
import { getPoliceOfficer } from "../../../api/epgms/police_officer/get.js";
import { postPopulationChange } from "../../../api/epgms/population_change/post.js";
import { dateChange } from "../../../api/epgms/datechange/change.js";
import { putPopulation } from "../../../api/epgms/population/put.js";
import { useStore } from "vuex";

// 表单数据
const form = ref({
  idNumber: "",
  stationName: "",
  householdNumber: "",
  name: "",
  ethnicity: "",
  gender: "",
  changeDate: "",
  changeType: "迁出",
  description: "",
  // newHouseholdNumber: "1188", //实验，先假设11是隔壁片区，22是本地
});

// 搜索数据
const formData = ref({
  idNumber: "",
});

const formRef = ref();
const formRefData = ref();

const relationToHead = ref("");
const total = ref(0);
const isAlive = ref("");
const oldHouseNumber = ref(""); //迁出中可以死，死亡中无这一句
const personId = ref("");
const stationId = ref("");
const stationName = ref("");

// 搜索表单验证规则
const rulesFormData = {
  idNumber: [
    { required: true, message: "身份证号不能为空", trigger: "blur" },
    { pattern:/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
};

// 表单验证规则
const rules = {
  idNumber: [
    { required: true, message: "身份证号不能为空", trigger: "blur" },
  ],
  stationName: [
    { required: true, message: "派出所不能为空", trigger: "blur" },
  ],
  householdNumber: [
    { required: true, message: "所在户号不能为空", trigger: "blur" },
  ],
  name: [
    { required: true, message: "姓名不能为空", trigger: "blur" },
  ],
  gender: [
    { required: true, message: "性别不能为空", trigger: "blur" },
  ],
  ethnicity: [
    { required: true, message: "民族不能为空", trigger: "blur" },
  ],
  changeDate: [
    { required: true, message: "变动日期不能为空", trigger: "blur" },
  ],
  changeType: [
    { required: true, message: "变动类别不能为空", trigger: "blur" },
  ],
  description: [
    { required: true, message: "变动原因不能为空", trigger: "blur" },
  ],
};

// const resetList =()=>{
//   form.value.name=""
//   form.value.idNumber=""
//   form.value.pageNum=1
//   form.value.pageSize=10
//   fetchData()
// }

const store = useStore();
const userName = store.getters.userName;
const officerInfo = store.getters.officerInfo;
// 搜索处理
const handleSearch = async () => {
  form.value = {
    idNumber: "",
    stationName: "",
    householdNumber: "",
    name: "",
    ethnicity: "",
    gender: "",
    changeDate: "",
    changeType: "迁出",
    description: "",
  };
  formRefData.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await getPopulation({
          idNumber: formData.value.idNumber,
        });
        relationToHead.value = response.data.data[0].relationToHead;
        stationName.value = officerInfo.policeStation.name;
        stationId.value = officerInfo.stationId;
        console.log(
          "取得的station: " +
            stationName.value +
            "和" +
            stationId.value,
        );

        console.log(response.data.data[0].isAlive);
        if (response.data.data[0].isAlive == "死亡") {
          ElMessage.error("该居民不具备迁出条件(状态：死亡)");
        } else if (response.data.data[0].householdNumber == "") {
          ElMessage.error("该居民不具备迁出条件(状态：迁出中)");
        } else {
          isAlive.value = response.data.data[0].isAlive;
          oldHouseNumber.value =
            response.data.data[0].householdNumber;
          if (
            response &&
            response.data.code === 2000 &&
            response.data
          ) {
            personId.value = response.data.data[0].personId;

            form.value.stationName = stationName.value;
            form.value.idNumber = response.data.data[0].idNumber;
            form.value.householdNumber =
              response.data.data[0].householdNumber;
            form.value.name = response.data.data[0].name;
            form.value.ethnicity = response.data.data[0].ethnicity;
            form.value.gender = response.data.data[0].gender;
            form.value.householdNumber =
              response.data.data[0].householdNumber;

            console.log("直接获取station测试:", form.value); // 桩
          } else {
            console.error("搜索失败或格式不正确");
          }

          // if (
          //   respolice &&
          //   respolice.data.code === 2000 &&
          //   respolice.data
          // ) {
          //   form.value.stationId = respolice.data.data[0].stationId;
          //   console.log("最终表单:", form.value); // 桩
          // } else {
          //   console.error("搜索失败或格式不正确");
          // }
        }
      } catch (error) {
        console.error("搜索失败:", error);
        if (error.message=="TypeError: Cannot read properties of null (reading '0')"){
          ElMessage.error("居民不存在");
        }
      }
    } else {
      console.log("搜索表单验证失败");
    }
  });
};

const onSubmit = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (relationToHead.value === "户主") {
        ElMessage.error("户主不可迁出！");
      } else {
        console.log(isAlive.value + oldHouseNumber.value);
        if (isAlive.value == "死亡") {
          //应该不可能用上
          ElMessage.error("该居民不具备迁出条件(状态：死亡)");
        } else if (oldHouseNumber.value == "") {
          ElMessage.error("该居民不具备迁出条件(状态：迁出中)");
        } else {
          try {
            console.log("变量personId:", personId.value); // 桩
            const resmodify = await putPopulation({
              personId: personId.value,
              householdNumber: "",
            });

            if (resmodify && resmodify.data.code === 2000) {
              console.log("已去除户号:", form.value); // 桩
            } else {
              console.error("更改失败或格式不正确");
            }

            const reschange = await postPopulationChange({
              personId: personId.value,
              changeType: form.value.changeType,
              changeDate: new Date(
                form.value.changeDate,
              ).toISOString(),
              description: form.value.description,
              createdAt: new Date().toISOString(),
              handlingPoliceStationId: stationId.value,
              // newHouseholdNumber: form.value.householdNumber,
              oldHouseholdNumber: form.value.householdNumber,
            });
            console.log("返回" + reschange + reschange.data.code);
            if (reschange && reschange.data.code === 2000) {
              console.log("提交了记录:", form.value); // 桩
              ElMessage.success("提交成功");
              oldHouseNumber.value = "";
            } else {
              console.error("提交失败或格式不正确");
            }
          } catch (error) {
            console.error("提交失败:", error);
          }
        }
      }
    } else {
      console.log("表单验证失败");
    }
  });
};

const reset = () => {
  form.value = {
    idNumber: "",
    stationName: "",
    householdNumber: "",
    name: "",
    ethnicity: "",
    gender: "",
    changeDate: "",
    changeType: "迁出",
    description: "",
  };
  formData.value = {
    idNumber: "",
  };
};
</script>

<style scoped>
.center-head {
  display: block;
  /* 默认就是block，但这里明确一下 */
  margin-left: 40%;
  margin-right: 40%;
  width: 20%;
}

.center-line {
  display: block;
  /* 默认就是block，但这里明确一下 */
  margin-left: 20%;
  margin-right: 5%;
  width: 90%;
}

/* 子界面自适应 */
.parent-container {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 100vh;
  /* 视口高度 */
  box-sizing: border-box;
}

.form-container {
  width: 90%;
  padding: 20px;
  box-sizing: border-box;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.submit-button {
  margin-left: 23%;
  margin-right: 25%;
  /* 调整两个按钮之间的间距 */
}
</style>

<!-- <script>
import { ref } from "vue";
import { getPopulation } from "../../../../api/population/get.js";

export default {
  data() {
    return {
      form: {
        person_id: "", //看情况，大概放到上搜索框
        station_id: "",
        household_number: "根据读取填充",
        name: "",
        address: "根据读取填充",
        sex: "",
        resource: "",
        change_date: "",
        change_type: "户口迁出",
        description: "",
      },
      formData: {
        query: "",
      },
    };
  },
  methods: {
    handleSearch() {
      // 用来进行搜索请求的函数
      this.fetchSearchResults(this.formData.query)
        .then((response) => {
          // 将返回的数据更新到主表单中
          this.form.name = response.name;
          this.form.sex = response.sex;
          this.form.change_date = response.change_date;
          this.form.person_id = response.person_id;
          this.form.station_id = response.station_id;
        })
        .catch((error) => {
          console.error("搜索失败:", error);
        });
    },
    fetchSearchResults(query) {
      // 模拟一个后台请求，这里query是handleSearch中调用时输入的参数，这里是形参名
      //改axios
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          // 模拟返回数据
          if (query === "114514") {
            resolve({
              name: "测试用户",
              sex: "男",
              change_date: new Date(2024, 6, 1),
              person_id: query,
              station_id: "31415",
            });
            //月份好像默认从0开始
          } else {
            reject("没有找到匹配的数据");
          }
        }, 1000);
      });
    },

    onSubmit() {
      console.log("OK!", this.form);
    },
  },
};
</script> -->
